<template>
  <div style="height: 100%">
    <g-dynamic-table
      type="user-logs"
      ref="table"
      :fetch="fetchDataList"
      @action-click="handleActionClick"
      rowKey="userId"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'result'">
          <span>{{ l(record.result) }}</span>
        </template>
        <template v-if="column.key === 'actions'">
          <div>
            <a
              class="table-edit"
              v-if="isGranted('Pages.Administration.LoginLogs.LogingLogs')"
              @click="logsDetails(record)"
            >
              <edit-outlined />
              {{ l('LoginLogs') }}
            </a>
          </div>
        </template>
      </template>
    </g-dynamic-table>
  </div>
</template>
<script lang="ts">
  import dayjs from 'dayjs';
  import { defineComponent } from 'vue';
  import { AppComponentBase } from '/@/shared/component-base';
  import { LoginLogsServiceProxy } from '/@/shared/service-proxies';
  import { LoginLogsDto } from '/@/shared/service-proxies/service-proxies';
  import LogDetailsCompent from './log-details/log-details.vue';
  import GDynamicTable from '/@/shared/components/g-dynamic-table/index.vue';
  import { EVENT_BTN_ENUM } from '/@/shared/components/g-dynamic-table/enums/event-btn-enum';
  import { jsonToSheetXlsx } from '/@/components/Excel';
  dayjs.locale('zh-cn');

  export default defineComponent({
    components: {
      GDynamicTable,
      LogDetailsCompent,
    },
    name: 'user-logs-news',
    mixins: [AppComponentBase],
    data() {
      return {
        userLogsService: new LoginLogsServiceProxy(),
        selectItems: [] as any[],
        item: {} as LoginLogsDto,
      };
    },
    methods: {
      /**
       * 获取数据
       */
      fetchDataList() {
        const { maxResultCount, skipCount, DateRange, UserName } = (
          this.$refs.table as any
        ).getSearchProps();
        return new Promise((resolve, reject) => {
          this.userLogsService
            .getPageUserLog(
              UserName,
              !DateRange ? undefined : DateRange[0],
              !DateRange ? undefined : DateRange[1],
              maxResultCount,
              skipCount,
            )
            .finally(() => {
              // finishedCallback!();
            })
            .then((res) => {
              resolve(res);
              // this.showPaging(res);
            })
            .catch((error) => {
              reject(error);
            });
        });
      },
      //模态框弹出
      logsDetails(item?: LoginLogsDto): void {
        this.modalHelper
          .create(
            LogDetailsCompent,
            { id: item?.userId, userName: item?.userName },
            {
              width: '800px',
            },
          )
          .subscribe(() => {});
      },
      //action操作回调
      handleActionClick(event: string, item?: any) {
        console.log(event);
        switch (event) {
          case EVENT_BTN_ENUM.LoginStatisticsUser:
            this.logsDetails(item);
            break;
          case EVENT_BTN_ENUM.LoginStatisticsAll:
            this.logsDetails();
            break;
          case EVENT_BTN_ENUM.EXPORT:
            const { username, maxResultCount, skipCount } = (
              this.$refs.table as any
            ).getSearchProps();
            (this.$refs.table as any).setLoading(true);
            this.userLogsService
              .getPageUserLog(username, undefined, undefined, maxResultCount, skipCount)
              .then((res) => {
                const data = res?.items.map((item: LoginLogsDto) => {
                  const obj: any = item;
                  obj.creationTime = dayjs(obj.creationTime).format('YYYY-MM-DD HH:mm:ss');
                  obj.lastLoginTime = dayjs(obj.lastLoginTime).format('YYYY-MM-DD HH:mm:ss');
                  obj.result = this.l(obj.result);
                  return obj;
                });
                console.log(data);

                jsonToSheetXlsx({
                  data,
                  filename: '登录日志.xlsx',
                });
                abp.notify.success(this.l('ExportSuccess'));
              })
              .catch((err) => {
                abp.notify.warn(err.message);
              })
              .finally(() => {
                (this.$refs.table as any).setLoading(false);
              });
            break;
          case EVENT_BTN_ENUM.BULK_EXPORT:
            let table: any = this.$refs.table as any;
            table.setLoading(true);
            this.userLogsService
              .getPageUserLog(undefined, undefined, undefined, table.pagination.total, 1)
              .then((res) => {
                const data = res?.items.map((item: LoginLogsDto) => {
                  const obj: any = item;
                  obj.creationTime = dayjs(obj.creationTime).format('YYYY-MM-DD HH:mm:ss');
                  obj.lastLoginTime = dayjs(obj.lastLoginTime).format('YYYY-MM-DD HH:mm:ss');
                  obj.result = this.l(obj.result);
                  return obj;
                });
                console.log(data);

                jsonToSheetXlsx({
                  data,
                  filename: '所有登录日志.xlsx',
                });
                abp.notify.success(this.l('ExportSuccess'));
              })
              .catch((err) => {
                abp.notify.warn(err.message);
              })
              .finally(() => {
                (this.$refs.table as any).setLoading(false);
              });
            break;
          default:
            break;
        }
      },
    },
  });
</script>
